package com.example.firstproject.controller;

import com.example.firstproject.common.WrapMapper;
import com.example.firstproject.common.Wrapper;
import com.example.firstproject.entity.User;
import com.example.firstproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: lihua
 * @Date: 2024/4/15 10:51
 * @Version: v1.0.0
 * @Description:
 **/

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private  RedisTemplate redisTemplate;

    @PreAuthorize("hasRole('ROLE_admin')")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Wrapper<Object> userRegister(@RequestBody User user){


        return WrapMapper.ok();
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Wrapper userLogin(@RequestBody User user, HttpSession session){
        UsernamePasswordAuthenticationToken unauthenticated = UsernamePasswordAuthenticationToken.
                unauthenticated(user.getUsername(), user.getPassword());
        try {
            Authentication authenticate = authenticationManager.authenticate(unauthenticated);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
            return WrapMapper.ok();
        } catch (AuthenticationException e) {
            return WrapMapper.error();
        }
    }

    @GetMapping("/user")
    public Wrapper<List<User>> getAllUser(){
        List<User> users = userService.getAllUser();
        if( users == null){
            return WrapMapper.error("查询为空");
        }else {
            for (User user : users){
                user.setPassword("***");
            }
            return WrapMapper.ok(users);
        }
    }
}
